<?php
namespace app\api\Controller;
use think\Controller;
use think\Db;
use think\Request;
use think\View;
class Jiapu extends Index
{
	public function __construct(Request $request)
	{
		parent::__construct($request);
		if(!session('userid'))
		{
			jsBack('您还未登录','/api/register/index');
			return false;
		}
	}
	/**
	* 管理家谱
	*/
	public function jiapuList()
	{
		//家谱
		$jiapu=Db::name('jiapu')->where(['userid'=>session('userid')])->find();
		$personnel=Db::name('personnel')->where(['jiapuid'=>$jiapu['jiapuid']])->select();
		$tree = $this->getTree($personnel, 0);
		// dump($tree);
		$this->assign('tree',$tree);
		return view('jiapulist');
	}
	/**
	* 递归查询，类内调用
	*/
	private function getTree($personnel,$personnelpid)
	{
		$tree = '';
		foreach($personnel as $k => $v){
		  if($v['personnelpid'] == $personnelpid){        //父亲找到儿子
		   $v['personnelp'] = $this->getTree($personnel, $v['personnelid']);
		   $tree[] = $v;
		  }
		}
		return $tree;
	}
	/**
	* 创建家谱
	*/
	public function jiapuAdd()
	{
		$user=Db::name('user')->where(['userid'=>session('userid')])->find();
		$this->assign('user',$user);
		return view('jiapuadd');
	}
	/**
	* 创建家谱过程
	*/
	public function jiapuinsert()
	{
		Db::startTrans();
		try{
			//家谱数据
			$data['jiapuname']=input('jiapuname');
			$data['addtime']=time();
			$data['userid']=session('userid');
			$jiapu=Db::name('jiapu')->insertGetid($data);
			// 本人
			$data2['personnelname']=input('post.myname');
			$data2['sex']=input('post.sex');
			$data2['birthday']=strtotime(input('post.birthday'));
			$data2['relation']=0;
			$data2['personnelpid']=0;
			$data2['jiapuid']=$jiapu;
			$oneself=Db::name('personnel')->insertGetid($data2);
			//父亲的数据
			$data3['personnelname']=input('post.fathername');
			$data3['sex']=0;
			$data3['birthday']=strtotime(input('post.fatherbirthday'));
			$data3['relation']=1;
			$data3['personnelpid']=$oneself;
			$data3['jiapuid']=$jiapu;
			$father=DB::name('personnel')->insertGetid($data3);
			$data4['personnelname']=input('post.mathername');
			$data4['sex']=1;
			$data4['birthday']=strtotime(input('post.matherbirthday'));
			$data4['relation']=2;
			$data4['personnelpid']=$oneself;
			$data4['jiapuid']=$jiapu;
			$father=DB::name('personnel')->insertGetid($data4);
		    // 提交事务
		    Db::commit();
		    jsBack('添加成功','/api/jiapu/jiapulist');    
		} catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		    jsBack('数据有误');
		}
	}
	/**
	* 完善家谱
	*/ 
	public function wanshan()
	{

	} 
}